package com.lxzh123;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

public class NotePad extends Activity{
	public static final String DB_NAME="NotePad.db";
	public static final int VERSION=1;
//	public DatabaseHelper mHelper=new DatabaseHelper(this,DB_NAME, null, VERSION);
	
	private static final int List_ID=Menu.FIRST;//定义菜单序号	
	//标题和内容文本框
	private EditText mTitleText;
	private EditText mContentText;
	
	private String filepath=android.os.Environment.getExternalStorageDirectory()+"/NotePad";
	private String FILE_NAME="/newText";
	private boolean isfileexists=false;
	final String TAG="I/O";
	private String fileCode="UTF-8";
    
    OnClickListener btnClick;
    Button saveButton;
    Button historyButton;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        LxzhApplication.getInstance().addActivity(this);
        
        mTitleText=(EditText)findViewById(R.id.title);
        mContentText=(EditText)findViewById(R.id.content);
        mContentText.setGravity(Gravity.TOP);   //设置文本从第一行开始
        
        saveButton=(Button)findViewById(R.id.save);   
        historyButton = (Button)findViewById(R.id.history);
        saveButton.getBackground().setAlpha(100);
        historyButton.getBackground().setAlpha(100);
        
        //接收从ViewFile传过来的待编辑文件路径
        Intent intent=getIntent();
        String filename=intent.getStringExtra("filename");
        if(filename!=null)
        {
        	mTitleText.setText(filename.substring(filename.lastIndexOf("/")+1, filename.lastIndexOf(".")));
        	fileCode=EncodingDetect.getJavaEncode(filename);
        	String fileContent = getStringFromFile(filename);
            mContentText.setText(fileContent);  
            LxzhApplication.getInstance().exit(this);
        }
     
        //按钮事件响应处理
        btnClick=new OnClickListener(){
        	public void onClick(View v)
            {
            	if(v==saveButton)
            	{
            		String title=mTitleText.getText().toString();
                	String content=mContentText.getText().toString();
            		if(title.length()>0)
            		{
            			FILE_NAME="/"+title;
            		}
            		if(content.length()==0)
            		{
            			Toast.makeText(NotePad.this.getApplicationContext(),
            					R.string.dialog_inputagain, Toast.LENGTH_SHORT).show();
            			return;
            		}
            		else
            		{
            			createDialog();
            		}
            	}
            	else
            	{
            		Intent intent = new Intent(NotePad.this, HistoryList.class);
            		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
            		startActivity(intent);
            	}
        	}
        };
        /*设置事件单击接口*/
        saveButton.setOnClickListener(btnClick);
        historyButton.setOnClickListener(btnClick);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       /* 	if(requestCode == 0) {
            	if(resultCode == Activity.RESULT_OK) {          
            	Bundle bundle=data.getExtras();
            	mTitleText.setText(bundle.getString("filename"));
            	Toast.makeText(NotePad.this.getApplicationContext(),
            			bundle.getString("filename"), Toast.LENGTH_SHORT).show();
                SharedPreferences preferences = getSharedPreferences("Text", 0);
                filenameString=preferences.getString("text", null);
                mTitleText.setText(preferences.getString("text", null));
                String fileContent = getStringFromFile(bundle.getString("filename"));
                mContentText.setText(fileContent);
            	}
        	}
    	super.onActivityResult(requestCode, resultCode, data);*/
    }
    
    //创建对话框，询问用户是否确实要保存数据
    public void createDialog()
    {
    	File fileDirs=new File(filepath);
		if(!fileDirs.exists())
		{
			fileDirs.mkdirs();
		}	
		isfileexists=false;
		AlertDialog.Builder builder=new AlertDialog.Builder(this);
		builder.setTitle(R.string.dialog_message_save).setCancelable(false)
			   .setPositiveButton(
    			R.string.dialog_yes,
    			new DialogInterface.OnClickListener()
    			{	
					public void onClick(DialogInterface dialog, int id) {
						// TODO Auto-generated method stub]
						savefile();
					}
				}).setNegativeButton(R.string.dialog_no, 
						 new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});
		File file=new File(filepath + FILE_NAME+".txt");
		if(file.exists())
		{
			isfileexists=true;
			builder.setMessage(R.string.dialog_exists).setTitle(R.string.dialog_prompt)
			.setMessage(R.string.dialog_exists).setCancelable(true);
		}
    	AlertDialog alert=builder.create();
    	alert.show();
    }

    public void savefile()
    {
    	try
		{
    		String path=filepath + FILE_NAME+".txt";
    		File file=new File(path);
    		isfileexists=file.exists();
    		
    		FileOutputStream fOS = new FileOutputStream(
					path);
			fOS.write(mContentText.getText().toString().getBytes());
			fOS.close();
			//关闭文件file的OutputStream 
    		
	        if(isfileexists)
	        {
	        	Toast.makeText(NotePad.this.getApplicationContext(),
	        			R.string.dialog_savecover_success, Toast.LENGTH_SHORT).show();
	        }     
	        //不存在则向数据库添加数据
	        else 
	        {
	        	Toast.makeText(NotePad.this.getApplicationContext(),
						R.string.dialog_savenew_success, Toast.LENGTH_SHORT).show();
	        }
		}
		catch(IOException e)
		{
			Toast.makeText(NotePad.this.getApplicationContext(),
					R.string.dialog_save_failure, Toast.LENGTH_SHORT).show();
		}	
    }
    
    //添加菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	menu.add(0, 1, 0, R.string.menu_about).setIcon(R.drawable.ic_about);
    	menu.add(0, 2, 0, R.string.menu_adddate).setIcon(R.drawable.ic_adddate);
    	menu.add(0, 3, 0, R.string.menu_clear).setIcon(R.drawable.ic_clearall);
    	menu.add(0, 4, 0, R.string.menu_quit).setIcon(R.drawable.ic_quit);
    	return true;
    }
    
    //定制各菜单响应
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch(item.getItemId())
    	{
    		case 1: createMenuDialog(1); return true;
    		case 2: addDate();return true;
    		case 3: clearAll();return true;
    		case 4: createMenuDialog(4);return true;
    		default:return false;
    	}
    }
    
    //清空标题栏与文本框里的内   
    public void clearAll()
    {
    	mTitleText.setText("");
    	mContentText.setText("");
    }
    
    //在光标处添加当前日期
    public void addDate()
    {
    	Date now=new Date();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
    	int coursorIndex=mContentText.getSelectionStart();
    	StringBuffer content=new StringBuffer(mContentText.getText().toString());
    	content.insert(coursorIndex, sdf.format(now));
    	mContentText.setText(content);
    	mContentText.setSelection(coursorIndex+10, coursorIndex+10);
    }
    
  //创建菜单对话框  
    public void createMenuDialog(int Item)
    {
    	AlertDialog.Builder builder=new AlertDialog.Builder(this);
		if(Item==1)
    	{
    		builder.setIcon(R.drawable.ic_notepad)
     	   .setTitle(R.string.menu_about)
     	   .setMessage("记事本  android2.2\n\nwww.lxzh123.com\n© 2012 龙心之火\n\nAll rights reserved");
    	}
    	else
    	{
    		builder.setMessage(R.string.dialog_message_quit).setCancelable(false).setPositiveButton(
        			R.string.dialog_yes,
        			new DialogInterface.OnClickListener() {
    					
    					public void onClick(DialogInterface dialog, int id) {
    						// TODO Auto-generated method stub
    						LxzhApplication.getInstance().exit();
    					}
    				}).setNegativeButton(R.string.dialog_no,
        			new DialogInterface.OnClickListener() {
    					
    					public void onClick(DialogInterface dialog, int id) {
    						// TODO Auto-generated method stub	
    						dialog.cancel();
    					}
    				});
    	}
    	AlertDialog alert=builder.create();
    	alert.show();	
    }
    
    //读取文件内容
    public String getStringFromFile(String filepath)
    {
    	try
    	{
    		this.setTitle(filepath);
			StringBuffer sBuffer = new StringBuffer();
			FileInputStream fInputStream = new FileInputStream(filepath);
			InputStreamReader inputStreamReader = new InputStreamReader(fInputStream, fileCode);
			BufferedReader in = new BufferedReader(inputStreamReader);
			if(!new File(filepath).exists())
			{
				return null;
			}
			while (in.ready()) {
				sBuffer.append(in.readLine() + "\n");
			}
			in.close();
			return sBuffer.toString();
		} 
    	catch (Exception e) 
    	{
			e.printStackTrace();
		}
		return null;
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        if (keyCode == KeyEvent.KEYCODE_BACK&& event.getRepeatCount() == 0) 
        {
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);  
        	builder.setTitle(R.string.dialog_message_quit);  
            builder.setPositiveButton(R.string.dialog_yes, new  DialogInterface.OnClickListener() 
            {  
                public void onClick(DialogInterface dialog, int which) {  
                    finish();  
                }  
            });  
            builder.setNegativeButton(R.string.dialog_no, new DialogInterface.OnClickListener() 
            {  
                public void onClick(DialogInterface dialog, int which) {  
                	dialog.cancel();
                }  
            });  
            builder.create().show();  
            return true;
        }
        else return super.onKeyDown(keyCode, event);
    }
}